package com.woniuxy.login.util;

import com.alibaba.fastjson.JSON;
import com.woniuxy.login.util.param.MsgParam;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Date: 2021/7/7:16:25  <br/>
 * Description:
 */
@Component
public class SendMsgUtil {
     public static void sedMsg(String phone ,String code ) throws Exception{
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        URI uri = null;
        try {
            // 设置uri信息
            uri = new URIBuilder().setScheme("http").setHost("pub.woniulab.com").setPort(8081)
                    .setPath("/msg/sendMsg").build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        MsgParam param = new MsgParam();
        param.setCode(code);//支持[0-9][a-z][A-Z]
        param.setPhoneNum(phone);//发送手机号码
        // 创建Post请求
        HttpPost httpPost = new HttpPost(uri);
        StringEntity entity = new StringEntity(JSON.toJSONString(param), "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
